package com.youbug.system.controller;


import com.youbug.system.entity.Menu;
import com.youbug.system.service.IMenuService;
import com.youbug.common.vo.R;
import com.youbug.system.vo.MenusForRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author sunwx
 * @since 2022-12-05
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @GetMapping("/getMenus")
    public R<List<Menu>> getMenus(){

        List<Menu> menus = menuService.getMenus(null);

        return R.ok(menus);
    }
    @GetMapping("/getMenusWithLevel")
    public R<List<Menu>> getMenusWithLevel(){

        List<Menu> menus = menuService.getMenusWithLevel(null);

        return R.ok(menus);
    }

    @GetMapping("/getParentMenus")
    public R<List<Menu>> getParentMenus(){

        List<Menu> menus = menuService.getParentMenus(null);

        return R.ok(menus);
    }

    @GetMapping("/getMenusForRole/{roleId}")
    public R<List<Long>> getMenusForRole(@PathVariable Long roleId){

        List<Long> menuIds = menuService.getMenusForRole(roleId);

        return R.ok(menuIds);
    }

    @PostMapping("/saveMenusForRole")
    public R<Boolean> saveMenusForRole(@RequestBody MenusForRoleVo menusForRoleVo){

        Boolean save = menuService.saveMenusForRole(menusForRoleVo);

        return R.ok(save);
    }

    @GetMapping("/getMenu/{id}")
    public R<Menu> getMenu(@PathVariable String  id){

        Menu user = menuService.getById(id);

        return R.ok(user);
    }

    @PostMapping("/add")
    public R<Boolean> add(@RequestBody Menu menu){

        if(menu.getParentId() == null){
            menu.setParentId(0L);
            menu.setParentFullId("0");
        }
        String parentFullId = menu.getParentFullId()+"|";

        menu.setLevel(parentFullId.split("\\|").length);
        menu.setParentFullId(parentFullId);

        boolean save = menuService.save(menu);

        return  R.ok(save);
    }
    @GetMapping("/delete/{id}")
    public R<Boolean> add(@PathVariable String  id){

        boolean remove = menuService.removeById(id);

        return  R.ok(remove);
    }

    @PostMapping("/update")
    public R<Boolean> update(@RequestBody Menu menu){

        boolean save = menuService.updateById(menu);

        return  R.ok(save);
    }
}

